package proyectosdcliente;

import java.net.*;

public class Timeout extends Thread
{
    private int timeoutMillis = 0;
    private DatagramSocket socket;
    private int alertPort;

    public Timeout(int port, int timeoutSeconds)
    {
        timeoutMillis = timeoutSeconds * 1000;
        alertPort = port;
        try {
          socket = new DatagramSocket(1234);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public int getPort(){
        return socket.getPort();
    }

    @Override
    public void run()
    {
        if(timeoutMillis != 0)
            try
            {
              DatagramPacket packet = new DatagramPacket(new byte[10],10);
              socket.setSoTimeout(timeoutMillis);
              socket.receive(packet);
            } catch (Exception e) {
                try {
                    socket.connect(InetAddress.getLocalHost(), alertPort);
                    socket.send(new DatagramPacket("3;12:34".getBytes(), 7));
                    socket.disconnect();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            } finally {
                socket.close();
                timeoutMillis = 0;
            }
    }
}

